import { IDesignDataItem } from '@/appUtils/appData/designData'
import { ICaptureResponseEventData } from '@/components/WebExplorer/utils/interfaces'
import { useDesignStore } from '@/stores/design'
import { ElButton, ElMessage, ElNotification } from 'element-plus'
import { h } from 'vue'
import { ILanhuJsonRes } from '../../appUtils/appData/lanhuTypes'
import { ILanhuResult } from '../../appUtils/appData/lanhuTypes2'

const notificationCache: Record<string, boolean> = {}

export const lanhuResponseHandler = async (res: ICaptureResponseEventData<ILanhuResult>) => {
    // console.log(data.url, data.response)
    const data = res.response.result
    if (!data) return
    // 拿出versions
    const versions = data.versions
    if (!versions || !versions.length) return
    // 找到最新的版本
    const latestId = data.latest_version
    const latestVersion = versions.find((v) => v.id === latestId)
    if (!latestVersion) return

    // 拿到图片和json url
    const { url, json_url } = latestVersion

    if (!url || !json_url) return

    const jsonRes = await fetch(json_url)
    const json = (await jsonRes.json()) as ILanhuJsonRes

    if (!json) return

    // const tempArr: string[] = []
    // 第一轮筛选，把有切图的都筛选出来
    const idCache: Record<string, boolean> = {}
    const hasImageInfos = json.info.filter((v) => {
        // TODO: 这里的筛选切图有问题
        if (v.image) {
            idCache[v.id] = true
            // const name = v.name
            // const size = `${v.image.size.width}x${v.image.size.height}`
            // console.log
            // tempArr.push(`${name} ${size}`)
            return true
        }
        return false
    })

    // 第二轮筛选，把parentId为切图的都筛掉，并添加面积选项，后面根据面积排序
    const finalImageInfos = hasImageInfos.filter((v) => {
        const width = v.image?.size.width || 0
        const height = v.image?.size.height || 0
        v.area = width * height
        if (v.parentID && idCache[v.parentID]) {
            return false
        }
        return true
    })

    // 根据面积排序
    finalImageInfos.sort((a, b) => {
        const areaA = a.area || 0
        const areaB = b.area || 0
        return areaB - areaA
    })

    json.info = []

    const designData: IDesignDataItem = {
        id: data.id,
        name: data.name,
        latestVersionId: latestId,
        version: latestVersion,
        jsonData: json,
        infos: finalImageInfos
    }

    const cacheKey = `${designData.id}-${designData.infos.length}`

    if (notificationCache[cacheKey]) {
        return
    }
    notificationCache[cacheKey] = true

    // 保存数据
    const notification = ElNotification({
        title: `发现设计稿 ${designData.name}`,
        duration: 0,
        onClose: () => {
            notificationCache[cacheKey] = false
        },
        message: h('div', null, [
            h('div', null, `共有 ${designData.infos.length} 张切图`),
            h(
                ElButton,
                {
                    type: 'primary',
                    onClick: async () => {
                        const store = useDesignStore()
                        const res = await store.handleCapturedData(designData)
                        notification.close()
                        const text = res === 'add' ? '添加' : '更新'
                        ElMessage.success(`${text}成功`)
                        notificationCache[cacheKey] = false
                    }
                },
                '保存'
            )
        ])
    })
}
